package com.vcredit.creditcat.web;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vcredit.creditcat.model.SmsPsendLog;
import com.vcredit.creditcat.service.PersonInfoService;
import com.vcredit.creditcat.service.SMSService;
import com.vcredit.creditcat.vo.BatchSendSmsInputVo;
import com.vcredit.creditcat.vo.BatchSendSmsLogVo;

@Controller
@RequestMapping("message/sms")
public class SMSController {
	
	@Autowired
	private SMSService smsService;
	
	@Autowired
	private PersonInfoService personInfoService;
	
	@RequestMapping("page")
	public String toPage() {
		return "message/sms";
	}

	@RequestMapping("list")
	@ResponseBody
	public List<BatchSendSmsLogVo> list() {
		List<BatchSendSmsLogVo> result = new ArrayList<BatchSendSmsLogVo>();
		// 查询最近5个批次发送记录
		List<SmsPsendLog> unDownList = smsService.queryList();
		for (SmsPsendLog smsPsendLog : unDownList) {
			String content = smsPsendLog.getContent();
			Boolean status = smsPsendLog.getStatus();
			String sameOperateNo = smsPsendLog.getSameOperateNo();
			Integer position = smsPsendLog.getPosition();
			Integer num = smsPsendLog.getNum();
			
			// 已发送数量
			Long doneCount = (long)(position + num);
			Long unDoneCount = 0L;
			if(!status) {
				Long total = personInfoService.querytotal();
				unDoneCount = total - doneCount;
			}
			
			result.add(new BatchSendSmsLogVo(sameOperateNo, content, status, doneCount, unDoneCount));
		}
		return result;
	}
	
	@RequestMapping("batchSend")
	@ResponseBody
	public String batchSend(@Valid @RequestBody BatchSendSmsInputVo param) {
		try {
			Boolean result = smsService.batchSendSms(param);
			if(result) {
				return "success";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "fail";
	}
}
